package cn.simon.free.sensitive.core;

import cn.simon.free.sensitive.annotation.Sensitive;
import cn.simon.free.sensitive.annotation.SensitiveType;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.ContextualSerializer;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Objects;

/**
 * 脱敏工具类
 *
 * @author: simon
 * @date: 2018/12/14 1:26
 * @Copyright:
 * @modifier:
 * @motto a no talent, people who have to study hard
 */
@Component
public class SensitiveUtils extends JsonSerializer<String> implements
        ContextualSerializer {

    private SensitiveType type;

    private SensitiveUtils() {
    }

    private SensitiveUtils(final SensitiveType type) {
        this.type = type;
    }

    /**
     * [中文姓名] 只显示第一个汉字，其他隐藏为2个星号<例子：李**>
     *
     * @param fullName
     * @return
     */
    public static String chineseName(String fullName) {
        if (StringUtils.isBlank(fullName)) {
            return "";
        }
        String name = StringUtils.left(fullName, 1);
        return StringUtils.rightPad(name, StringUtils.length(fullName), "*");
    }

    /**
     * [身份证号] 显示最后四位，其他隐藏。共计18位或者15位。<例子：*************5762>
     *
     * @param id
     * @return
     */
    public static String idCardNum(String id) {
        if (StringUtils.isBlank(id)) {
            return "";
        }
        String num = StringUtils.right(id, 4);
        return StringUtils.leftPad(num, StringUtils.length(id), "*");
    }

    /**
     * [固定电话] 后四位，其他隐藏<例子：****1234>
     *
     * @param num
     * @return
     */
    public static String fixedPhone(String num) {
        if (StringUtils.isBlank(num)) {
            return "";
        }
        return StringUtils.leftPad(StringUtils.right(num, 4), StringUtils.length(num), "*");
    }

    /**
     * [手机号码] 前三位，后四位，其他隐藏<例子:138******1234>
     *
     * @param num
     * @return
     */
    public static String mobilePhone(String num) {
        if (StringUtils.isBlank(num)) {
            return "";
        }
        return StringUtils.left(num, 3).concat(StringUtils.removeStart(StringUtils.leftPad(StringUtils.right(num, 4), StringUtils.length(num), "*"), "***"));
    }

    /**
     * [地址] 只显示到地区，不显示详细地址；我们要对个人信息增强保护<例子：北京市海淀区****>
     *
     * @param address
     * @return
     */
    public static String address(String address) {
        if (StringUtils.isBlank(address)) {
            return "";
        }
        //敏感信息长度
        int prefecture = StringUtils.indexOf(address, "县");
        int district = StringUtils.indexOf(address, "区");
        int city = StringUtils.indexOf(address, "市");
        int province = StringUtils.indexOf(address, "省");
        if (prefecture != -1) {
            return addr(address, prefecture);
        }
        if (district != -1) {
            return addr(address, district);
        }
        if (city != -1) {
            return addr(address, city);
        }
        if (province != -1) {
            return addr(address, province);
        }
        return address;
    }

    private static String addr(String address, int sensitiveSize) {
        String left = StringUtils.left(address, sensitiveSize | 1);
        return StringUtils.rightPad(left, StringUtils.length(left) + 5, "*");
    }

    /**
     * [电子邮箱] 邮箱前缀仅显示第一个字母，前缀其他隐藏，用星号代替，@及后面的地址显示<例子:g**@163.com>
     *
     * @param email
     * @return
     */
    public static String email(String email) {
        if (StringUtils.isBlank(email)) {
            return "";
        }
        int index = StringUtils.indexOf(email, "@");
        if (index <= 1) {
            return email;
        } else {
            return StringUtils.rightPad(StringUtils.left(email, 1), index, "*").concat(StringUtils.mid(email, index, StringUtils.length(email)));
        }
    }

    /**
     * [银行卡号] 前六位，后四位，其他用星号隐藏每位1个星号<例子:6222600**********1234>
     *
     * @param cardNum
     * @return
     */
    public static String bankCard(String cardNum) {
        if (StringUtils.isBlank(cardNum)) {
            return "";
        }
        return StringUtils.left(cardNum, 6).concat(StringUtils.removeStart(StringUtils.leftPad(StringUtils.right(cardNum, 4), StringUtils.length(cardNum), "*"), "******"));
    }

    @Override
    public void serialize(String value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        switch (this.type) {
            case CHINESE_NAME: {
                gen.writeString(SensitiveUtils.chineseName(value));
                break;
            }
            case ID_CARD: {
                gen.writeString(SensitiveUtils.idCardNum(value));
                break;
            }
            case MOBILE_PHONE: {
                gen.writeString(SensitiveUtils.mobilePhone(value));
                break;
            }
            case FIXED_PHONE: {
                gen.writeString(SensitiveUtils.fixedPhone(value));
                break;
            }
            case ADDRESS: {
                gen.writeString(SensitiveUtils.address(value));
                break;
            }
            case EMAIL: {
                gen.writeString(SensitiveUtils.email(value));
                break;
            }
            case BANK_CARD: {
                gen.writeString(SensitiveUtils.bankCard(value));
                break;
            }
        }
    }

    @Override
    public JsonSerializer<?> createContextual(SerializerProvider prov, BeanProperty property) throws JsonMappingException {
        if (property != null) {
            if (Objects.equals(property.getType().getRawClass(), String.class)) {
                Sensitive sensitiveInfo = property.getAnnotation(Sensitive.class);
                if (sensitiveInfo == null) {
                    sensitiveInfo = property.getContextAnnotation(Sensitive.class);
                }
                if (sensitiveInfo != null) {
                    return new SensitiveUtils(sensitiveInfo.name());
                }
            }
            return prov.findValueSerializer(property.getType(), property);
        }
        return prov.findNullValueSerializer(null);
    }
}